package com.jy.app.lib.biz;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.jy.app.lib.application.BaseApplication;
import com.jy.app.lib.base.Constants;
import com.jy.app.lib.base.TokenConfig;
import com.jy.app.lib.bean.BaseResponse;
import com.jy.app.lib.cache.ACache;
import com.jy.app.lib.cache.MCache;
import com.jy.app.lib.net.HttpUtil;
import com.jy.app.lib.net.TokenHandler;
import com.jy.app.lib.utils.JsonUtil;
import com.jy.app.lib.utils.LogUtil;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;

import static com.jy.app.lib.net.HttpUtil.logD;
import static com.jy.app.lib.net.HttpUtil.setAsyncHttpHeaders;

public class TokenBizManager extends MCache {

    private static TokenBizManager instance;
    private static ACache aCache;
    private static TokenConfig mTokenConfig;

    private TokenBizManager() {
    }

    public static TokenBizManager getInstance() {
        if (instance == null) {
            instance = new TokenBizManager();
        }
        if (aCache == null) {
            aCache = ACache.get(BaseApplication.appContext);
        }
        if(mTokenConfig==null){
            mTokenConfig =new TokenConfig(BaseApplication.appContext);
        }
        return instance;
    }
    /**
     * 更新token
     * @param handler
     */
    public void updataToken(final TokenHandler handler) {
        if(TextUtils.isEmpty(BaseApplication.updataTokenURL)){
            LogUtil.w("you forget define the url for token");
            handler.onSuccess(false);
            return;
        }
        long time = mTokenConfig.getTime();
        long dif = time - new Date().getTime();
        logD("updataToken","time dif=>"+dif);
        if (dif >= Constants.TOKEN_DIF_TIME) {
            handler.onSuccess(false);
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", mTokenConfig.getUserName());
        map.put("password", mTokenConfig.getPassword());
        map.put("isToken","false");
        setAsyncHttpHeaders(map);
        logD("updataToken","--request="+JsonUtil.toJson(map));
        AsyncHttpClient httpClient =  HttpUtil.getInstance();
        httpClient.removeAllHeaders();
        httpClient.post(BaseApplication.mAppContext, BaseApplication.updataTokenURL, new StringEntity(JsonUtil.toJson(map), HttpUtil.ENCODE), HttpUtil.CONTENT_TYPE, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    String successContent = new String(bytes, HttpUtil.ENCODE);
                    logD("updataToken","successContent="+successContent);
                    BaseResponse<String> res = JSON.parseObject(successContent, new TypeReference<BaseResponse<String>>() {
                    });
                    if (res.getCode() == 0) {
                        JSONObject jsonObject = new JSONObject(res.getData());
                        String token = jsonObject.getString("token");
                        mTokenConfig.setToken(token);
                        mTokenConfig.setTime(new Date().getTime());
                        handler.onSuccess(true);
                    } else {
                        handler.onFailure(res.getCode(), res.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.onFailure(10000, "数据异常");
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                logD("updataToken","onFailure");
                handler.onFailure(10000, "网络连接异常 "+i);
            }
        });
    }

    public void  hanlerSimpleToken(Context context, final Map params, final SimplerTokenListener listener){
        try {
            if (!params.containsKey("isToken")) {
                TokenBizManager.getInstance().updataToken(new TokenHandler() {
                    @Override
                    public void onSuccess(boolean flag) {
                        setAsyncHttpHeaders(params);
                        RequestParams rp = new RequestParams(params);
                        if(listener!=null){
                            listener.onUpdateSuccess(rp,false);
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        if(listener!=null){
                            listener.onUpdateFail(code,msg);
                        }
                    }
                });
            } else {
                setAsyncHttpHeaders(params);
                RequestParams rp = new RequestParams(params);
                if(listener!=null){
                    listener.onNotUpdate(rp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface SimplerTokenListener{
        void onUpdateSuccess(RequestParams requestParams, boolean flag);
        void onUpdateFail(int code, String msg);
        void onNotUpdate(RequestParams requestParams);
    }
}
